L2-050 懂蛇语
题目 L2-050 懂蛇语
思路分析
代码实现
使用multimap
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
using ll = long long;
using ull = unsigned long long;
using PII = pair<int,int>;
using Pll = pair<ll,ll>;
int dx[4]= {-1,0,-1,0},dy[4]= {0,1,0,-1};
const int inf = 0x3f3f3f3f;
multimap<string,string> hx;
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin>>n;
cin.ignore();
while(n--) { //nm的 首字母放空格
string s;
getline(cin,s);
string ssm;
for(int i=0; i<s.size(); i++) {
if(i==0 && s[i]!=' ') ssm+=s[i];
else if(i>0 && s[i-1]==' ' && s[i]!=' ') ssm+=s[i];
}
hx.insert({ssm,s});
}
int m;
cin>>m;
cin.ignore();
while(m--) {
string tmp;
getline(cin,tmp);
string q;
for(int i=0; i<tmp.size(); i++) {
if(i==0 && tmp[i]!=' ') q+=tmp[i];
else if(i>0 && tmp[i-1]==' ' && tmp[i]!=' ') q+=tmp[i];
}
auto range=hx.equal_range(q);
if(range.first==range.second) {
cout<<tmp<<endl;
} else {
vector<string> ans;
for(auto it=range.first; it!=range.second; it++) {
ans.push_back(it->second);
}
sort(ans.begin(),ans.end());
for(int i=0; i<ans.size(); i++) {
if(i>0) cout<<"|";
cout<<ans[i];
}
cout<<endl;
}
}
return 0;
}
使用map<string, vector
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
using ll = long long;
using ull = unsigned long long;
using PII = pair<int,int>;
using Pll = pair<ll,ll>;
int dx[4]= {-1,0,-1,0},dy[4]= {0,1,0,-1};
const int inf = 0x3f3f3f3f;
map<string, vector<string>> hx;
string getInitials(const string& s) {
string res;
for(int i = 0; i < s.size(); ++i) {
if((i == 0 && s[i] != ' ') || (i > 0 && s[i-1] == ' ' && s[i] != ' '))
res += s[i];
}
return res;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
cin.ignore();
while(n--) {
string s;
getline(cin, s);
string initials = getInitials(s);
hx[initials].push_back(s);
}
for(auto& v : hx) {
sort(v.second.begin(), v.second.end());
}
int m;
cin >> m;
cin.ignore();
while(m--) {
string tmp;
getline(cin, tmp);
string q = getInitials(tmp);
if(hx.count(q) == 0) {
cout << tmp << endl;
} else {
const vector<string>& ans = hx[q];
for(int i = 0; i < ans.size(); ++i) {
if(i > 0) cout << "|";
cout << ans[i];
}
cout << endl;
}
}
return 0;
}
同类题型
视频讲解
⬅️ L2-049 鱼与熊掌 🏠 00-天梯赛 ➡️ multimap多值查询
💬 评论